package cn.jeefast.rest.controller;

import cn.jeefast.common.entity.*;
import cn.jeefast.rest.dao.MbPatientDao;
import cn.jeefast.rest.dao.MbResearchDataDao;
import cn.jeefast.rest.dao.MbResearchStepDao;
import cn.jeefast.rest.service.MbResearchService;
import cn.jeefast.rest.service.MbResearchSetpDataDetailService;
import cn.jeefast.rest.util.ExportExcelUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import cn.jeefast.common.utils.R;
import cn.jeefast.rest.annotation.AuthIgnore;
import cn.jeefast.rest.annotation.LoginUser;
import cn.jeefast.rest.entity.TbToken;
import cn.jeefast.rest.entity.TbUser;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.activation.URLDataSource;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URL;
import java.util.*;

/**
 * API测试接口
 *
 * @author theodo
 * @email 36780272@qq.com
 * @date 2017-10-23 15:47
 */
@RestController
@RequestMapping("/api")
public class ApiTestController {

    @Autowired
    private MbPatientDao mbPatientDao;

    @Autowired
    private MbResearchStepDao researchStepDao;

    @Autowired
    private MbResearchDataDao mbResearchDataDao;

    @Autowired
    private MbResearchSetpDataDetailService researchSetpDataDetailService;

    @Autowired
    private MbResearchService mbResearchService;

    /**
     * 获取用户信息
     */
    @GetMapping("userInfo")
    public R userInfo(@LoginUser TbUser user){
        return R.ok().put("user", user);
    }

    /**
     * 获取用户ID
     */
    @GetMapping("userId")
    public R userInfo(@RequestAttribute("userId") Integer userId){
        return R.ok().put("userId", userId);
    }

    /**
     * 忽略Token验证测试
     */
    @AuthIgnore
    @GetMapping("notToken")
    public R notToken(){
        return R.ok().put("msg", "无需token也能访问。。。");
    }

    /**
     * 接收JSON数据
     */
    @PostMapping("jsonData")
    public R jsonData(@LoginUser TbUser user, @RequestBody TbToken token){
        return R.ok().put("user", user).put("token", token);
    }

    /**
     * Excel导出
     * @param pid
     * @param request
     * @param response
     * @return
     */
    @AuthIgnore
    @RequestMapping(value = "/exportHandConf", method = { RequestMethod.POST, RequestMethod.GET })
    public @ResponseBody
    JSONObject exportHandConf(Long pid, HttpServletRequest request,
                              HttpServletResponse response,
                              String img1)
    {
        JSONObject result = new JSONObject();

        //根据患者ID查询已审核过的阶段
        EntityWrapper ew = new EntityWrapper();
        ew.eq("patient_id",pid);
        ew.eq("state",3);
        List<MbResearchData> list = mbResearchDataDao.selectList(ew);
        //获取周期列表
        List<String> r = new ArrayList();
        List<List> l = new ArrayList<>();
        for (MbResearchData mrd:list) {
            EntityWrapper ew1 = new EntityWrapper();
            ew1.eq("data_detail_id",mrd.getDataId());
            List list1 = researchSetpDataDetailService.selectList(ew1);
            l.add(list1);
            MbResearchStep mbResearchStep = researchStepDao.selectById(mrd.getResStepId());
            r.add(mbResearchStep.getStepName());
        }

        //填充数据
        List<Map<String, Object>> maps =
                new ArrayList<>();
        for (List<List> li:l) {
            //循环取库里的记录
            Map map = new HashMap();
            for (int i=0;i<li.size();i++) {
                MbResearchSetpDataDetail mbResearchSetpDataDetail = (MbResearchSetpDataDetail) li.get(i);
                map.put(i,mbResearchSetpDataDetail.getDdValue());
            }
            maps.add(map);
        }
        if (maps.size() != 0)
        {
            try
            {
                String title = "导出";
                String[] rowsName = new String[] { "周期", "ALB(g/L)", "CRP(mg/L)", "TCHO(mmol/L)", "LDL-C(mmol/L)", "HDL-C(mmol/L)", "SCR(μmol/L)", "BUN(mmol/L)", "BUN(mmol/L)", "P(mmol/L)","",""};
                List<Object[]> dataList = new ArrayList<Object[]>();
                Object[] objs = null;
                for (int i = 0; i < maps.size(); i++)
                {
                    objs = new Object[rowsName.length];
                    objs[0] = r.get(i);
//                    objs[1] = maps.get(i).get("headUrl");   //头像url
                    objs[1] = maps.get(i).get(0);   //头像url
                    objs[2] = maps.get(i).get(1);
                    objs[3] = maps.get(i).get(2);
                    objs[4] = maps.get(i).get(3);
                    objs[5] = maps.get(i).get(4);
                    objs[6] = maps.get(i).get(5);
                    objs[7] = maps.get(i).get(6);
                    objs[8] = maps.get(i).get(7);
                    objs[9] = maps.get(i).get(8);
                    if(i==0){
                        if(img1!=null){
                            objs[10] = img1;
                        }else{
                            objs[10] = null;
                        }
                    }
                    dataList.add(objs);
                }
                ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, dataList, response);
                ex.exportData();
            }
            catch (Exception e)
            {
                e.printStackTrace();

            }

        }
        try {
            result.put("flag", "true");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.println(result.toString());
        return result;
    }

    /**
     * 邮件发送
     * @return
     */
    @RequestMapping("/mail")
    public R send(Long pid,String img,String email) throws Exception{
        System.out.println("sendMailServlet-----start2");

        //1.创建邮件对象
        Properties properties = new Properties();
        properties.put("mail.smtp.host", "smtp.163.com"); // 指定SMTP服务器
        properties.put("mail.smtp.auth", "true"); // 指定是否需要SMTP验证
        Session session = Session.getInstance(properties);
        MimeMessage message =new MimeMessage(session);

        /*2.设置发件人
         * 其中 InternetAddress 的三个参数分别为: 邮箱, 显示的昵称(只用于显示, 没有特别的要求), 昵称的字符集编码
         * */
        message.setFrom(new InternetAddress("anewhen@163.com","anewhen","UTF-8"));
        /*3.设置收件人
        To收件人   CC 抄送  BCC密送*/
        message.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(email,"manbing","UTF-8"));
//        message.addRecipient(MimeMessage.RecipientType.TO,new InternetAddress("17862****9@qq.com","xiuhong","UTF-8"));

        /*4.设置标题*/
        message.setSubject("附件导出下载","UTF-8");
        //message.setContent("Test Content:这是一封测试邮件...","text/html;charset=UTF-8");

        /*5.设置邮件正文*/

        //一个Multipart对象包含一个或多个bodypart对象，组成邮件正文
        MimeMultipart multipart = new MimeMultipart();
        //读取本地图片,将图片数据添加到"节点"
//        MimeBodyPart image = new MimeBodyPart();
//        DataHandler dataHandler1 = new DataHandler(new FileDataSource("C:\\Users\\Chen Xiuhong\\Pictures\\suo.png"));
//        DataHandler dataHandler1 = new DataHandler(new FileDataSource("C:\\Users\\Chen Xiuhong\\Pictures\\suo.png"));
//        image.setDataHandler(dataHandler1);
//        image.setContentID("image_suo");

        //创建文本节点
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("请在附件中下载相关报表。及时下载，以免失效","text/html;charset=UTF-8");

        //创建附件节点  读取本地文件,并读取附件名称
//        MimeBodyPart file1 = new MimeBodyPart();
//        DataHandler dataHandler2 = new DataHandler(new FileDataSource("C:\\Users\\Chen Xiuhong\\Pictures\\clothes.png"));
//        file1.setDataHandler(dataHandler2);
//        file1.setFileName(MimeUtility.encodeText(dataHandler2.getName()));

        MimeBodyPart file2 = new MimeBodyPart();
        URL url = new URL("http://localhost:7081/jeefast-rest/api/exportHandConf?pid="+pid+"&img1="+img);
        DataHandler dataHandler3 = new DataHandler(new URLDataSource(url));
        file2.setDataHandler(dataHandler3);
//        file2.setFileName(MimeUtility.encodeText(dataHandler3.getName()));
        file2.setFileName(MimeUtility.encodeText("报表.xls"));


        //将文本和图片添加到multipart
        multipart.addBodyPart(text);
//        multipart.addBodyPart(image);
//        multipart.addBodyPart(file1);
        multipart.addBodyPart(file2);
        multipart.setSubType("mixed");//混合关系

        message.setContent(multipart);

        message.setSentDate(new Date());
        message.saveChanges();
        Transport transport = session.getTransport("smtp");
        transport.connect("smtp.163.com","anewhen@163.com","Aa01Bb02");
        transport.sendMessage(message,message.getAllRecipients());
        transport.close();
        Boolean isFlag = true;
//        logger.info(Calendar.getInstance().getTime()+" : # Send mail to "+" success #");

        System.out.println("sendMailServlet-----end2");
        return R.ok("");
    }
}
